package com.jhhc.BDMS.File;

import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.jhhc.BDMS.File.Pojo.BDMS_SYS_FILE_D;
import com.jhhc.BDMS.File.Server.BDMS_SYS_FILE_DService;
import com.jhhc.BDMS.File.Pojo.result.FileResult;
import com.jhhc.RHDB.Data.Pojo.ST_TIDE_H;
import com.jhhc.RHDB.Data.Service.ST_TIDE_HService;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Pojo.BDMS_ST_ASTROTD_F;
import com.jhhc.StormSurgeForecast.AstronomicalTide.Util.GetInformTxtUtil;
import com.jhhc.StormSurgeForecast.StormSurge.Pojo.BDMS_ST_TIDE_E;
import com.jhhc.utils.JsonResult;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;
import java.io.File;
import java.text.SimpleDateFormat;

/**
 * @author wrk
 */
@Api(value="文件处理",tags={"文件处理"})
@RestController
@RequestMapping(value = "BDMS/File",headers = "Accept=application/json")
public class FileUploadController {

    @Autowired
    private BDMS_SYS_FILE_DService bdms_sys_file_dService;
    @Autowired
    private ST_TIDE_HService st_tide_hService;
    SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @ApiOperation(value = "上传文件")
    @PostMapping("/Upload")
    public JsonResult uploadFile( @RequestParam("projectId") int projectId,@RequestParam("file") MultipartFile file) throws Exception{
        JsonResult jsonResult = new JsonResult();
        // 检查文件是否为空
        if (file.isEmpty()) {
            jsonResult.setStatusCode(200);
            jsonResult.setSucceeded(true);
            jsonResult.setData("请选择要上传的文件");
            return jsonResult;
        }
            // 获取文件的字节数组
            String fileName =file.getOriginalFilename();
            String fileExtension = null;
            if (fileName != null) {
                fileExtension = fileName.substring(fileName.lastIndexOf(".") + 1);
                System.out.println(fileExtension);
                //根据fileExtension（扩展名）判断文件
                switch (fileExtension){
                    case "json":
                    case "JSON":
                        List<ST_TIDE_H> st_tide_hList =new ArrayList<>();
                        //整编表导入
                        // 将字节数组转换为字符串
                        // 获取上传的文件内容
                        String jsonContent = new String(file.getBytes());
                        // 将JSON字符串解析为JSONObject对象
                        JSONObject jsonObject = JSON.parseObject(jsonContent);
                        // 获取JSON中的字段值
                        List<ST_TIDE_H> st_tide_hs = jsonObject.getList("RECORDS",ST_TIDE_H.class);
                        int count = 0;
                        int res =0;
                        for (ST_TIDE_H sttideh : st_tide_hs) {
                            ST_TIDE_H st_tide_h = new ST_TIDE_H();
                            st_tide_h.setStcd(sttideh.getStcd());
                            st_tide_h.setTm(sttideh.getTm());
                            st_tide_h.setTdz(sttideh.getTdz());
                            if (!"".equals(String.valueOf(sttideh.getAirp()))){
                                st_tide_h.setAirp(sttideh.getAirp());
                            }
                            if (!"".equals(String.valueOf(sttideh.getTdchrcd()))){
                                st_tide_h.setTdchrcd(sttideh.getTdchrcd());
                            }
                            if (!"".equals(String.valueOf(sttideh.getTdptn()))){
                                st_tide_h.setTdptn(sttideh.getTdptn());
                            }
                            if (!"".equals(String.valueOf(sttideh.getHltdmk()))){
                                st_tide_h.setHltdmk(sttideh.getHltdmk());
                            }
                            st_tide_hList.add(st_tide_h);
                            // 处理每一行数据
                            // 每隔250行执行批量入库
                            count++;
                            if (count == 250) {
                                // 执行批量入库操作
                                int re =   st_tide_hService.insertBatchOrUpdate(st_tide_hList);
                                res += count+re;

                                // 清空列表和计数器
                                st_tide_hList.clear();
                                count = 0;
                            }
                        }
                        int res1=0;
                        // 如果最后一批数据不足250行，也执行批量入库
                        if (!st_tide_hList.isEmpty()) {
                            // 执行批量入库操作
                            res1 = st_tide_hService.insertBatchOrUpdate(st_tide_hList);
                        }
                        if (res+res1>0){
                            jsonResult.setData("数量处理共计："+((res/2)+res1)+"条");
                            jsonResult.setStatusCode(200);
                            jsonResult.setSucceeded(true);
                            return jsonResult;
                        }
                        break;
                    case "pdf":
                        // 在这里可以对文件进行处理，如保存到本地或其他操作
                        String uniqueId = UUID.randomUUID().toString();
                        // 创建文件夹
                        String folderPath =System.getProperty("user.dir")+"/"+"RSVR/"+projectId+"/" + uniqueId;

                        File folder = new File(folderPath);
                        if (!folder.exists()) {
                            folder.mkdirs();
                        }
                        //文件生成路径
                        String filePath = folderPath+"/" + fileName;
                        System.out.println(filePath);
                        //
                        File dest = new File(filePath);
                        file.transferTo(dest);
                        //生成文件后信息入库
                        BDMS_SYS_FILE_D bdmsSysFileD = new BDMS_SYS_FILE_D();
                        bdmsSysFileD.setPid(projectId);
                        bdmsSysFileD.setFileid(uniqueId);
                        bdmsSysFileD.setTm(format.format(new Date()));
                        bdmsSysFileD.setFilename(fileName);
                        bdmsSysFileD.setAbsolutePath(System.getProperty("user.dir"));
                        bdmsSysFileD.setRelativePath("RSVR/"+projectId);
                        System.out.println(bdmsSysFileD);
                        bdms_sys_file_dService.insert(bdmsSysFileD);

                        jsonResult.setStatusCode(200);
                        jsonResult.setSucceeded(true);
                        jsonResult.setData("文件上传成功");
                        return jsonResult;
                    default:
                        break;
                }
            }

        return null;
    }

    @ApiOperation(value = "获取文件列表")
    @PostMapping("/GetFiles")
    public JsonResult getFile(@RequestParam("projectId") int projectId) {
        JsonResult jsonResult = new JsonResult();
        List<FileResult> fileResults = new ArrayList<>();
        //根据项目id和文件id获取对应文件路径
        List<BDMS_SYS_FILE_D> bdmsSysFileDs = bdms_sys_file_dService.queryAll(projectId);
        for (BDMS_SYS_FILE_D bdmsSysFileD:bdmsSysFileDs){
            FileResult fileResult = new FileResult();
            //String filePath =  bdmsSysFileD.getAbsolutePath().replace("\\", "/")+"/"+bdmsSysFileD.getFileid()+"/"+bdmsSysFileD.getFilename();
            fileResult.setFileId(bdmsSysFileD.getFileid());
            //fileResult.setUser(bdmsSysFileD.get);
            fileResult.setTime(bdmsSysFileD.getTm());
            fileResult.setFileName(bdmsSysFileD.getFilename());
            fileResults.add(fileResult);
        }
        jsonResult.setData(fileResults);
        jsonResult.setSucceeded(true);
        jsonResult.setStatusCode(200);
        return jsonResult;
    }

    //文件转base64
    public static String fileToBase64(String filePath) {
        try {
            Path path = Paths.get(filePath);
            byte[] fileContent = Files.readAllBytes(path);
            return Base64.getEncoder().encodeToString(fileContent);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
    @ApiOperation(value = "获取文件内容")
    @GetMapping("/GetFileData")
    public JsonResult getFileData(@RequestParam("projectId") int projectId,@RequestParam("fileId") String fileId) {
        JsonResult jsonResult = new JsonResult();

        BDMS_SYS_FILE_D bdmsSysFileD = bdms_sys_file_dService.queryById(projectId,fileId);
        String filePath =  bdmsSysFileD.getAbsolutePath().replace("\\", "/")+"/"+bdmsSysFileD.getRelativePath().replace("\\","/")+"/"+bdmsSysFileD.getFileid()+"/"+bdmsSysFileD.getFilename();
        String base64String = fileToBase64(filePath);
        jsonResult.setData(base64String);
        jsonResult.setSucceeded(true);
        jsonResult.setStatusCode(200);
        return jsonResult;
    }

    //删除文件
    public static boolean deleteFolder(String folderPath) {
//        File file = new File(filePath);
//        if (file.exists()) {
//            if (file.delete()) {
//                System.out.println("文件删除成功！");
//                return true;
//            } else {
//                System.out.println("文件删除失败！");
//                return false;
//            }
//        } else {
//            System.out.println("文件不存在！");
//        }

        File folder = new File(folderPath);
        if (folder.exists()) {
            File[] files = folder.listFiles();
            if (files != null) {
                for (File file : files) {
                    if (file.isDirectory()) {
                        deleteFolder(file.getAbsolutePath());
                    } else {
                        file.delete();
                    }
                }
            }
            folder.delete();
            System.out.println("文件夹删除成功！");
            return true;
        } else {
            System.out.println("文件夹不存在！");
            return false;
        }

    }
    @ApiOperation(value = "删除文件信息")
    @GetMapping("/DeleteFiles")
    public JsonResult deleteFiles(@RequestParam("projectId") int projectId,@RequestParam("fileId") List<String>  fileIds) {
        JsonResult jsonResult = new JsonResult();


        //根据项目编号和fileids获取数据
        int i =0;
        List<BDMS_SYS_FILE_D> bdmsSysFileDs =bdms_sys_file_dService.queryByFileIds(projectId,fileIds);
        for (BDMS_SYS_FILE_D bdmsSysFileD:bdmsSysFileDs){
            System.out.println(bdmsSysFileD);
            System.out.println(bdms_sys_file_dService.queryById(projectId,bdmsSysFileD.getFileid()));
            String fileId =bdmsSysFileD.getFileid();
            String filePath =  bdmsSysFileD.getAbsolutePath().replace("\\", "/")+"/"+bdmsSysFileD.getRelativePath().replace("\\","/")+"/"+bdmsSysFileD.getFileid();
            if (deleteFolder(filePath)){
                int res = bdms_sys_file_dService.deleteById(projectId,fileId);
                i +=1;
            }
        }
        if (i>0){
            jsonResult.setData("文件删除成功");
            jsonResult.setSucceeded(true);
            jsonResult.setStatusCode(200);
        }
        return jsonResult;
    }
}